import pdfplumber

# 定义PDF文件路径
pdf_path = r"C:\Users\luojinying\Desktop\中集车辆：2023年年度报告.pdf"

# 打开PDF文件
with pdfplumber.open(pdf_path) as pdf:
    for page_number, page in enumerate(pdf.pages):
        # 提取当前页的文本
        text = page.extract_text()
        if text:
            # 预处理文本，去除多余的空格和换行符
            cleaned_text = ' '.join(text.split())
            print(f"Text from page {page_number + 1}:")
            print(cleaned_text)
        else:
            print(f"Page {page_number + 1} has no text or text extraction failed.")

        # 提取表格数据
        tables = page.extract_tables()
        for table_index, table in enumerate(tables):
            print(f"\nTable {table_index + 1} from page {page_number + 1}:")
            for row_index, row in enumerate(table):
                # 将None值转换为字符串''，确保所有元素都是字符串
                processed_row = ["" if cell is None else str(cell) for cell in row]
                try:
                    # 将处理后的行连接为一个字符串，以逗号分隔
                    row_str = ','.join(processed_row)
                    print(row_str)
                except TypeError as e:
                    # 如果仍然出现类型错误，打印详细的错误信息和行数据
                    print(f"Error processing row {row_index + 1} in table {table_index + 1} on page {page_number + 1}: {e}")
                    print(f"Processed row data: {processed_row}")

# 将提取的数据写入文件
with open('extracted_text.txt', 'w', encoding='utf-8') as f:
    with pdfplumber.open(pdf_path) as pdf:
        for page_number, page in enumerate(pdf.pages):
            text = page.extract_text()
            if text:
                cleaned_text = ' '.join(text.split())
                f.write(cleaned_text + '\n\n')

with open('extracted_tables.csv', 'w', encoding='utf-8') as f:
    with pdfplumber.open(pdf_path) as pdf:
        for page_number, page in enumerate(pdf.pages):
            tables = page.extract_tables()
            for table_index, table in enumerate(tables):
                for row_index, row in enumerate(table):
                    processed_row = ["" if cell is None else str(cell) for cell in row]
                    f.write(','.join(processed_row) + '\n')